package DFS;

/**
 * @Classname 岛屿数量200
 * @Description TODO
 * @Date 2023/3/15 20:12
 * @Created by xjl
 */
public class 岛屿数量200 {

    int[][] dist=new int[][]{{1,0},{0,1},{-1,0},{0,-1}};
    boolean[][] visit;

    public int numIslands(char[][] grid) {
        int count=0;
        int len=grid.length;
        int width=grid[0].length;
        boolean[][] visit=new boolean[len][width];
        for (int i=0;i<len;i++){
            for (int j=0;j<width;j++){
                if (!visit[i][j]&&grid[i][j]=='1'){
                    dfs(i,j,grid);
                    count++;
                }
            }
        }
        return count;
    }

    private void dfs(int i, int j, char[][] grid) {
        if (i<0||i>=grid.length||j<0||j>=grid[0].length||grid[i][j]=='0'){
            return;
        }
        visit[i][j]=true;
        grid[i][j]='0';
        for (int k=0;k<4;k++){
            int x=i+dist[k][0];
            int y=j+dist[k][1];
            dfs(x,y,grid);
        }
    }
}
